package com.atues.backtrack.combainationSum2;



import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @description:
 * @author: liang
 * @time: 2025-02-13 20:00
 */
class Solution {

    List<List<Integer>> res = new ArrayList<List<Integer>>();
    List<Integer> path = new ArrayList<Integer>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        int[] used = new int[candidates.length];
        backtracking(candidates,target,0,0,used);
        return res;
    }

    public void backtracking(int[] candidates, int target, int cSum,int start,int[]  used){
        if(cSum == target){
            res.add(new ArrayList<>(path));
            return;
        }
        if(cSum > target)return;
        for(int i = start; i < candidates.length; i ++){
            if(cSum + candidates[i] > target)break;
            if(i>=1 && candidates[i] == candidates[i-1] && used[i-1] == 0)continue;
            cSum+= candidates[i];
            used[i] = 1;
            path.add(candidates[i]);
            backtracking(candidates,target,cSum,i+1,used);
            path.remove(path.size()-1);
            cSum-=candidates[i];
            used[i] = 0;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] sum = {10, 1, 2, 7, 6, 1, 5};
        List<List<Integer>> lists = solution.combinationSum2(sum, 8);
        System.out.println(JSON.toJSONString(lists));
    }
}